//three只处理添加成员，其中可填名字，必选关系

const app = getApp()
let saving = false

Page({
  data: {
    name: '',
    relation: '',
    infoId: '',
    openid: '',
    code: '',
    icode: '',
    iname: '',
    b2a: '',
    rel: '',
    men: '',
    info: '',
  },

  onLoad(x) {
    this.setData({
      openid: x.openid,
      infoId: x.infoId,
      icode: x.code,
      iname: x.name,
      code: x.co
    })
    console.log('infoId：', this.data.infoId, '。icode：', this.data.icode, '。iname：', this.data.iname, '。openid：', this.data.openid)
  },
  onReady() {
    app.getMyInfo().then(i => {
      if (i.relations) {
        const kk = Object.values(i.relations)
        .filter(x => x.a === this.data.icode)
        .map(x=> ({rel: x.a2b, name: i.members[x.b].name}))
        console.log(kk)
        this.setData( {
          info: kk,
        })  
      }
    })
  },
  xingming(x){
    this.setData( {
      name: x.detail.value
    })
  },
  guanxi(x){
    let b2a =  x.detail.value
    if (b2a === '父母'){
      b2a = '子女'
    }else if (b2a === '子女'){
      b2a = '父母'
    }
    this.setData( {
      relation: x.detail.value,
      b2a: b2a,
    })
  },
  onAdd() {
    if (saving){
      return
    }
    saving = true
    if (this.data.name === '' || this.data.relation === '') {
      // 提示框
      wx.showToast({
        icon: 'none',
        title: '关系和姓名不能为空',
      })
      saving = false
      return
    }
    const code = app.genertCode()
    const number = app.genertCode()
    const db = wx.cloud.database()
    db.collection('information').doc(this.data.infoId).update({
      data: {
        members: {
          [code]:{
            code: code,
            name: this.data.name,
          }
        },
        relations: {
          [number]:{
            code: number,
            a: this.data.icode,
            b: code,
            a2b: this.data.relation,
            b2a: this.data.b2a,
          }
        }
      },
    })
    app.globalData.refresh = true
    this.setData({
      code,
    })
    wx.showToast({
      title: '添加成员信息成功',
    })
    console.log('[数据库] [新增记录] 成功， code: ', this.data.code)
    saving = false
    wx.redirectTo({
      url: '../../index/index'
    })
  },
})


// console.log("拿到的编码====", app.genertCode());